package com.bbs.security;

import com.bbs.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class TokenFilter extends GenericFilterBean {
    @Autowired
    TokenProvider tokenProvider;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //从Cookie中获取token
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        Cookie[] cookies = httpRequest.getCookies();
        String token = null;

        if(cookies != null){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("TOKEN")){
                    token = cookie.getValue();
                }
            }
        }

        if(token != null){
            //获取用户信息
            Authentication authentication = tokenProvider.parserToken(token);
            if(authentication != null){
                SecurityContext context = SecurityContextHolder.createEmptyContext();
                context.setAuthentication(authentication);
                SecurityContextHolder.setContext(context);

                System.out.println("当前用户:" + authentication);
            }
        }

        chain.doFilter(request, response);
    }
}
